package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.MyBussiesException;
import com.itheima.common.R;
import com.itheima.dto.SetmealDto;
import com.itheima.mapper.SetmealMapper;
import com.itheima.pojo.Setmeal;
import com.itheima.pojo.SetmealDish;
import com.itheima.service.SetmealDishService;
import com.itheima.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Override
    @Transactional
    public void saveWithSetmealDish(SetmealDto setmealDto) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDto, setmeal);
        setmealService.save(setmeal);
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmeal.getId());
            setmealDishService.save(setmealDish);
        }
    }

    @Override
    public R deleteWithSetmealDish(List<Long> ids) {
        QueryWrapper<Setmeal> queryWrapper = new QueryWrapper<>();
        //where id in ids；
        queryWrapper.in("id",ids);
        //where status = 1；
        queryWrapper.eq("status",1);
        //select count（*） from setmeal
        int count = setmealService.count(queryWrapper);
        if (count >0){
            //有套餐在售卖中--不能删除
           throw  new MyBussiesException("有套餐在售卖中--不能删除");
        }
        //可以删除
        setmealService.removeByIds(ids);
        //同时删除setmealDish表中的数据
        QueryWrapper<SetmealDish> wrapper = new QueryWrapper<>();
        wrapper.eq("setmeal_id",ids);
        setmealDishService.remove(wrapper);

        return R.success("删除成功");
    }
}
